import {createApp} from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
//1.引入element-plus组件库
import ElementPlus, {ElMessage} from 'element-plus'
import 'element-plus/dist/index.css'
//3.引入element-plus图标库
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
//5.1修改elementPlus默认中文
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import axios from "axios";
import res from "core-js/internals/is-forced";

const app = createApp(App)
//4.遍历ElementPlusIconsVue对象中的所有图标组件并注册到app中
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

//设置根路径
const BASE_URL = 'http://localhost:8080/';
window.BASE_URL = BASE_URL;
app.config.globalProperties.BASE_URL = BASE_URL;

//2.app.use(ElementPlus) 使用Element-plus组件库
//5.2 app.use(ElementPlus,{ locale: zhCn })将El本地化为中文
app.use(ElementPlus, {locale: zhCn}).use(store).use(router).mount('#app')

//6.解决ResizeObserver Error
const debounce = (fn, delay) => {
    let timer = null;
    return function () {
        let context = this;
        let args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(context, args);
        }, delay);
    }
}
const _ResizeObserver = window.ResizeObserver;
window.ResizeObserver = class ResizeObserver extends _ResizeObserver {
    constructor(callback) {
        callback = debounce(callback, 16);
        super(callback);
    }
}

//配置全局方法，获取当前登录人的数据
window.getUser = () => {
    return localStorage.user ? JSON.parse(localStorage.getItem('user')) : null;
}
window.getMerchant = async (merchant) => {
    let user = getUser();
    if (!user) {
        return {};
    }
    try {
        const res = await axios.get(BASE_URL + 'v1/backend/merchant/select',
            {params: {id: user.merchantId}})
        if (res.data.code === 2000) {
            merchant.value = res.data.data[0];
            // console.log(merchant.value);
        } else {
            ElMessage.error(res.data.msg);
        }
    } catch (error) {
        ElMessage.error(error.message);
    }
}

//设置路由守卫
router.beforeEach((to, from, next) => {
    let user = getUser();
    if (to.path !== '/login' && !user) {
        next({path: '/login'}, ElMessage.error('请先登录!'));
    } else if (to.path.startsWith('/merchant/') && user.type !== '1') {
        next({path: '/login'}, ElMessage.error('您不是商家管理员'));
    } else if (to.path.startsWith('/backend/') && user.type !== '0') {
        next({path: '/login'}, ElMessage.error('您不是平台管理员'));
    } else {
        next();
    }
})

window.loadEnum = (object, enumName) => {
    axios.get(BASE_URL + '/v1/enum/select/' + enumName)
        .then((response) => {
            if (response.data.code === 2000) {
                object.value = response.data.data;
            } else {
                ElMessage.error(response.data.message);
            }
        });
}

window.cellValueFormatter = (cellValue, arr) => {
    if (!arr.value) {
        return cellValue;
    }
    for (let item of arr.value) {
        if (item.value === cellValue) {
            return item.label;
        }
    }
    return cellValue;
}

//在 Axios 请求拦截器中统一附加 Token
axios.interceptors.request.use(
    config => {
        const token = localStorage.getItem('jwtToken');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    });




